using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;


namespace NEX_Datos
{
    public class ServicioEncriptacionRIJ
    {
        private static SymmetricAlgorithm alg;

        public static SymmetricAlgorithm Alg
        {
            get { return ServicioEncriptacionRIJ.alg; }
            set { ServicioEncriptacionRIJ.alg = value; }
        }

        private static byte[] fKey;
        public static String Key
        {
            get { return Convert.ToBase64String(ServicioEncriptacionRIJ.fKey); }
            set { 
                ServicioEncriptacionRIJ.fKey = Convert.FromBase64String(value);
                alg.Key = ServicioEncriptacionRIJ.fKey;
            }
        }

        public static String GenerarKey()
        {
            alg.GenerateKey();
            fKey = alg.Key;
            return Convert.ToBase64String(alg.Key);
        }

        public static String Encriptar(String textoAEncriptar)
        {
            byte[] textoPlano;
            textoPlano = System.Text.Encoding.UTF8.GetBytes(textoAEncriptar);
            ICryptoTransform cp = alg.CreateEncryptor(alg.Key, alg.IV);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, cp, CryptoStreamMode.Write);

            cs.Write(textoPlano, 0, textoPlano.Length);
            cs.FlushFinalBlock();

            return Convert.ToBase64String(ms.ToArray());

        }

        public static String Desencriptar(String textoADesencriptar)
        {
            byte[] textoCifrado;
            textoCifrado = Convert.FromBase64String(textoADesencriptar);
            ICryptoTransform cp = alg.CreateDecryptor(alg.Key, alg.IV);
            MemoryStream ms = new MemoryStream(textoCifrado);
            CryptoStream cs = new CryptoStream(ms, cp, CryptoStreamMode.Read);
            byte[] buffer = new byte[textoCifrado.Length];
            cs.Read(buffer, 0, buffer.Length);
            ms.Close();
            cs.Close();
            return System.Text.Encoding.UTF8.GetString(buffer);

        }
    }
}
